from PIL import Image, ImageDraw, ImageFont

fontsize=26
white = (255,255,255)

def get_font_render_size(text):
    canvas = Image.new('RGB', (2048,2048))
    draw = ImageDraw.Draw(canvas)
    monospace = ImageFont.truetype("fzhtjt.ttf", fontsize)
    draw.text((0, 0), text, font=monospace, fill=white)
    bbox = canvas.getbbox()
    # 宽高
    size = (bbox[2] - bbox[0], bbox[3] - bbox[1])
    return size


def add_text_to_image(image_path, text, output_path):
    # 打开图片
    img = Image.open(image_path)
    
    # 获取图片的宽度和高度
    width, height = img.size
    
    # 创建ImageDraw对象
    draw = ImageDraw.Draw(img)
    
    # 选择字体和字号
    # font = ImageFont.load_default()  # 你也可以选择其他字体，比如ImageFont.truetype("arial.ttf", 40)
    monospace = ImageFont.truetype("fzhtjt.ttf", fontsize)
    
    # 计算文字在图片中心的位置
    text_width, text_height = get_font_render_size(text)
   
    x = (width - text_width) // 2
    y = (height - text_height) // 2

    print(x,y)
    
    # 添加文字到图片中心
    draw.text((x, y), text, font=monospace, fill=255)  # fill参数指定文字颜色
    
    # 保存修改后的图片
    img.save(output_path)



# 使用示例
image_path = "bg.jpeg"
output_path = "output_image_with_text1.jpg"
text_to_add = "将从系统中清除。"

output_str = "白内障人群发病年龄多见于、40岁以上，其中60-8，9岁人群中，白内障发病率高、达80%" 
strs = output_str.split('、')
for index, s in enumerate(strs):
    if s:
        oPath = f'./output/{index}.png'
        print(s, index, oPath, '=============')
        add_text_to_image(image_path, s, oPath)
    else:
        print(f"Skipping empty string at index {index}")
   


# add_text_to_image(image_path, text_to_add, output_path)
